<template>
  <div class="knowledge-practice-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">知识点练习</h1>
      <div class="header-actions">
        <el-button @click="refreshPractice">
          <el-icon><Refresh /></el-icon>
          刷新练习
        </el-button>
        <el-button @click="viewPracticeHistory">
          <el-icon><History /></el-icon>
          练习历史
        </el-button>
      </div>
    </div>

    <!-- 知识点分类导航 -->
    <div class="category-navigation">
      <el-card class="category-card">
        <div class="category-header">
          <h2>知识点分类</h2>
          <el-select v-model="currentCategory" placeholder="选择分类" @change="onCategoryChange">
            <el-option label="全部" value="all" />
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </div>
        
        <div class="category-progress-list">
          <div
            v-for="category in categories"
            :key="category.id"
            :class="['category-progress-item', { 'active': currentCategory === category.id || (currentCategory === 'all' && category.id === defaultCategory) }]"
            @click="selectCategory(category.id)"
          >
            <div class="category-info">
              <div class="category-name">{{ category.name }}</div>
              <div class="category-stats">
                <span>已掌握: {{ category.masteredCount }}/{{ category.totalCount }}</span>
                <span>正确率: {{ category.correctRate }}%</span>
              </div>
            </div>
            <div class="category-progress">
              <el-progress
                :percentage="category.progressRate"
                :stroke-width="8"
                :color="getProgressColor(category.progressRate)"
                show-text
              />
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 练习模式选择 -->
    <div class="practice-mode-section">
      <el-card class="practice-mode-card">
        <h2 class="section-title">选择练习模式</h2>
        <div class="practice-mode-grid">
          <div
            v-for="mode in practiceModes"
            :key="mode.id"
            :class="['practice-mode-item', { 'active': currentMode === mode.id }]"
            @click="selectPracticeMode(mode.id)"
          >
            <div class="mode-icon">{{ mode.icon }}</div>
            <div class="mode-name">{{ mode.name }}</div>
            <div class="mode-description">{{ mode.description }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 题目设置 -->
    <div class="practice-settings-section">
      <el-card class="settings-card">
        <h2 class="section-title">练习设置</h2>
        <div class="settings-content">
          <div class="setting-group">
            <span class="setting-label">题目数量:</span>
            <el-input-number
              v-model="questionCount"
              :min="5"
              :max="50"
              :step="5"
              size="large"
            />
          </div>
          
          <div class="setting-group">
            <span class="setting-label">难度:</span>
            <el-rate v-model="difficultyLevel" :colors="['#67c23a', '#e6a23c', '#f56c6c']" />
          </div>
          
          <div class="setting-group">
            <span class="setting-label">出题偏好:</span>
            <el-radio-group v-model="questionPreference">
              <el-radio-button label="random">随机出题</el-radio-button>
              <el-radio-button label="weak">薄弱知识点</el-radio-button>
              <el-radio-button label="recent">近期学习</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 开始练习按钮 -->
    <div class="start-practice-section">
      <el-button
        type="primary"
        size="large"
        @click="startPractice"
        class="start-practice-btn"
        :loading="isLoading"
      >
        <el-icon><Play /></el-icon>
        开始练习
      </el-button>
    </div>

    <!-- 练习进行中 -->
    <div v-if="isPracticing" class="practicing-section">
      <el-card class="practicing-card">
        <!-- 练习进度 -->
        <div class="practice-progress-header">
          <div class="progress-info">
            <span class="progress-text">{{ currentQuestionIndex + 1 }}/{{ questions.length }} 题</span>
            <span v-if="practiceTimer > 0" class="timer-text">用时: {{ formatTime(practiceTimer) }}</span>
          </div>
          <div class="progress-buttons">
            <el-button size="small" @click="skipQuestion">跳过</el-button>
            <el-button size="small" danger @click="endPracticeEarly">结束练习</el-button>
          </div>
        </div>
        
        <!-- 题目内容 -->
        <div class="question-content">
          <div class="question-header">
            <span class="question-type">{{ getQuestionTypeName(currentQuestion.type) }}</span>
            <span class="question-difficulty" :class="`difficulty-${currentQuestion.difficulty}`">
              {{ getDifficultyText(currentQuestion.difficulty) }}
            </span>
          </div>
          
          <div class="question-stem">
            <h3>{{ currentQuestion.stem }}</h3>
            <div v-if="currentQuestion.imageUrl" class="question-image">
              <img :src="currentQuestion.imageUrl" :alt="currentQuestion.stem" />
            </div>
          </div>
          
          <!-- 选项 -->
          <div v-if="currentQuestion.options" class="question-options">
            <div
              v-for="(option, index) in currentQuestion.options"
              :key="index"
              :class="['option-item', { 'selected': selectedOptions.includes(index), 'disabled': isAnswered }]"
              @click="selectOption(index)"
            >
              <div class="option-label">{{ getOptionLabel(index) }}</div>
              <div class="option-content">{{ option }}</div>
            </div>
          </div>
          
          <!-- 填空/简答 -->
          <div v-else-if="currentQuestion.type === 'blank' || currentQuestion.type === 'essay'" class="question-answer-input">
            <el-input
              v-model="textAnswer"
              :type="currentQuestion.type === 'essay' ? 'textarea' : 'text'"
              placeholder="请输入答案"
              :autosize="currentQuestion.type === 'essay' ? { minRows: 4, maxRows: 8 } : false"
              :disabled="isAnswered"
            />
          </div>
          
          <!-- 题目解析 -->
          <div v-if="showExplanation" class="question-explanation">
            <h4>解析:</h4>
            <p>{{ currentQuestion.explanation }}</p>
            <div v-if="currentQuestion.isCorrect" class="correct-answer">
              正确答案: {{ getCorrectAnswerDisplay() }}
            </div>
          </div>
        </div>
        
        <!-- 题目操作按钮 -->
        <div class="question-actions">
          <div class="action-buttons">
            <el-button size="small" @click="toggleMark()">
              <el-icon>{{ isMarked ? 'StarFilled' : 'Star' }}</el-icon>
              {{ isMarked ? '取消标记' : '标记' }}
            </el-button>
            <el-button size="small" @click="toggleExplanation">
              <el-icon><Reading /></el-icon>
              {{ showExplanation ? '隐藏解析' : '查看解析' }}
            </el-button>
          </div>
          <div class="navigation-buttons">
            <el-button
              size="large"
              @click="prevQuestion"
              :disabled="currentQuestionIndex === 0"
            >
              <el-icon><ArrowLeft /></el-icon>
              上一题
            </el-button>
            <el-button
              v-if="!isAnswered"
              type="primary"
              size="large"
              @click="submitAnswer"
              :loading="isSubmitting"
            >
              提交答案
            </el-button>
            <el-button
              v-else
              type="primary"
              size="large"
              @click="nextQuestion"
              :disabled="currentQuestionIndex === questions.length - 1"
            >
              下一题
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 练习结果 -->
    <div v-if="showResult" class="practice-result-section">
      <el-card class="result-card">
        <div class="result-header">
          <h2 class="result-title">练习完成！</h2>
          <div class="result-stats">
            <div class="stat-item">
              <div class="stat-value">{{ correctCount }}</div>
              <div class="stat-label">正确题数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ incorrectCount }}</div>
              <div class="stat-label">错误题数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ skipCount }}</div>
              <div class="stat-label">跳过题数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ accuracyRate }}%</div>
              <div class="stat-label">正确率</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ formatTime(totalPracticeTime) }}</div>
              <div class="stat-label">总用时</div>
            </div>
          </div>
        </div>
        
        <div class="result-content">
          <!-- 正确率图表 -->
          <div class="chart-container">
            <h3>正确率分析</h3>
            <div class="chart-wrapper">
              <el-progress
                :percentage="accuracyRate"
                :format="formatProgress"
                :stroke-width="24"
                :color="getAccuracyColor(accuracyRate)"
              />
            </div>
          </div>
          
          <!-- 错题列表 -->
          <div v-if="incorrectQuestions.length > 0" class="incorrect-questions">
            <h3>错题回顾</h3>
            <div class="incorrect-questions-list">
              <div
                v-for="question in incorrectQuestions"
                :key="question.id"
                class="incorrect-question-item"
                @click="reviewIncorrectQuestion(question)"
              >
                <div class="incorrect-question-header">
                  <span class="question-number">第{{ question.index }}题</span>
                  <span class="question-type">{{ getQuestionTypeName(question.type) }}</span>
                </div>
                <div class="incorrect-question-stem">{{ question.stem }}</div>
              </div>
            </div>
          </div>
          
          <!-- 知识点掌握情况 -->
          <div class="knowledge-mastery">
            <h3>知识点掌握情况</h3>
            <div class="mastery-list">
              <div
                v-for="(mastery, categoryId) in categoryMastery"
                :key="categoryId"
                class="mastery-item"
              >
                <div class="mastery-info">
                  <span class="mastery-category">{{ getCategoryName(categoryId) }}</span>
                  <span class="mastery-rate">{{ mastery.correctRate }}%</span>
                </div>
                <el-progress
                  :percentage="mastery.correctRate"
                  :stroke-width="6"
                  :color="getMasteryColor(mastery.correctRate)"
                />
              </div>
            </div>
          </div>
        </div>
        
        <div class="result-actions">
          <el-button @click="reviewAllQuestions">
            <el-icon><Reading /></el-icon>
            查看全部题目
          </el-button>
          <el-button @click="saveToErrorBook">
            <el-icon><Document /></el-icon>
            保存到错题本
          </el-button>
          <el-button @click="practiceAgain">
            <el-icon><Refresh /></el-icon>
            再练一次
          </el-button>
          <el-button type="primary" @click="finishPractice">
            <el-icon><Check /></el-icon>
            完成
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox, ElProgress } from 'element-plus'
import {
  Refresh,
  ArrowLeft,
  ArrowRight,
  Reading,
  Document,
  Check
} from '@element-plus/icons-vue'

// 路由
// const router = useRouter()
// const route = useRoute()

// 响应式数据
const currentCategory = ref('all')
const currentMode = ref('standard')
const questionCount = ref(10)
const difficultyLevel = ref(2)
const questionPreference = ref('random')
const isLoading = ref(false)
const isPracticing = ref(false)
const showResult = ref(false)
const currentQuestionIndex = ref(0)
const selectedOptions = ref<number[]>([])
const textAnswer = ref('')
const isAnswered = ref(false)
const isSubmitting = ref(false)
const isMarked = ref(false)
const showExplanation = ref(false)
const practiceTimer = ref(0)
const totalPracticeTime = ref(0)
const timerInterval = ref<number | null>(null)

// 默认分类
const defaultCategory = '1'

// 知识点分类
const categories = ref([
  { id: '1', name: '图形推理', totalCount: 150, masteredCount: 90, correctRate: 75, progressRate: 60 },
  { id: '2', name: '定义判断', totalCount: 120, masteredCount: 85, correctRate: 80, progressRate: 70 },
  { id: '3', name: '类比推理', totalCount: 100, masteredCount: 80, correctRate: 90, progressRate: 80 },
  { id: '4', name: '逻辑判断', totalCount: 180, masteredCount: 95, correctRate: 70, progressRate: 53 },
  { id: '5', name: '言语理解', totalCount: 200, masteredCount: 110, correctRate: 65, progressRate: 55 },
  { id: '6', name: '数量关系', totalCount: 160, masteredCount: 60, correctRate: 50, progressRate: 38 },
  { id: '7', name: '资料分析', totalCount: 140, masteredCount: 100, correctRate: 85, progressRate: 71 }
])

// 练习模式
const practiceModes = ref([
  { id: 'standard', name: '标准练习', description: '按知识点随机出题', icon: '📝' },
  { id: 'timed', name: '计时练习', description: '限时完成，提升速度', icon: '⏱️' },
  { id: 'weak', name: '薄弱巩固', description: '针对薄弱知识点强化', icon: '🎯' },
  { id: 'review', name: '错题复习', description: '复习之前的错题', icon: '🔄' }
])

// 题目接口
interface Question {
  id: string
  stem: string
  type: 'single' | 'multiple' | 'blank' | 'essay'
  difficulty: 'easy' | 'medium' | 'hard'
  options?: string[]
  correctAnswers: number[] | string[]
  explanation: string
  categoryId: string
  knowledgePoints: string[]
  imageUrl?: string
  index?: number
  isCorrect?: boolean
  userAnswers?: any[]
}

// 练习记录接口
interface PracticeRecord {
  id: string
  categoryId: string
  mode: string
  questionCount: number
  correctCount: number
  incorrectCount: number
  skipCount: number
  accuracyRate: number
  totalTime: number
  startTime: Date
  endTime: Date
  questions: Question[]
}

// 模拟题目数据（作为后备数据）
const mockQuestions: Question[] = [
  {
    id: 'q1',
    stem: '从所给的四个选项中，选择最合适的一个填入问号处，使之呈现一定的规律性：\n图形：○ △ □ ○ △ ?',
    type: 'single',
    difficulty: 'easy',
    options: ['○', '△', '□', '◇'],
    correctAnswers: [2],
    explanation: '观察图形序列，发现是以○ △ □为周期循环出现的，所以△后面应该是□，正确答案为C选项。',
    categoryId: '1',
    knowledgePoints: ['图形推理', '周期性规律']
  },
  {
    id: 'q2',
    stem: '下列不属于哺乳动物特征的是：',
    type: 'single',
    difficulty: 'medium',
    options: ['胎生', '哺乳', '体温恒定', '用鳃呼吸'],
    correctAnswers: [3],
    explanation: '哺乳动物的主要特征包括胎生、哺乳、体温恒定等，而用鳃呼吸是鱼类的特征，所以正确答案为D选项。',
    categoryId: '2',
    knowledgePoints: ['生物学', '动物分类']
  },
  {
    id: 'q3',
    stem: '下列哪些属于清洁能源？（多选）',
    type: 'multiple',
    difficulty: 'medium',
    options: ['太阳能', '风能', '水能', '煤炭', '天然气'],
    correctAnswers: [0, 1, 2],
    explanation: '清洁能源是指不排放污染物、能够直接用于生产生活的能源，包括太阳能、风能、水能、生物能等。煤炭和天然气属于化石能源，燃烧会产生污染物，所以正确答案为A、B、C选项。',
    categoryId: '3',
    knowledgePoints: ['环境保护', '能源分类']
  },
  {
    id: 'q4',
    stem: '中国的首都是_________。',
    type: 'blank',
    difficulty: 'easy',
    correctAnswers: ['北京'],
    explanation: '北京是中华人民共和国的首都，是全国的政治中心、文化中心和国际交往中心。',
    categoryId: '4',
    knowledgePoints: ['地理', '中国国情']
  },
  {
    id: 'q5',
    stem: '简述影响气候的主要因素。',
    type: 'essay',
    difficulty: 'hard',
    correctAnswers: ['纬度位置、海陆位置、地形地势、洋流、人类活动等'],
    explanation: '影响气候的主要因素包括：\n1. 纬度位置：决定了太阳高度角和昼夜长短的变化，是影响气候的基本因素。\n2. 海陆位置：海洋和陆地的热力性质差异导致了沿海和内陆气候的不同。\n3. 地形地势：山脉对气流的阻挡作用、海拔高度的变化都会影响气候。\n4. 洋流：暖流增温增湿，寒流降温减湿。\n5. 人类活动：如温室气体排放、城市化等也会对气候产生影响。',
    categoryId: '5',
    knowledgePoints: ['地理', '气候学']
  }
]

// 练习题目列表
const questions = ref<Question[]>([])
const practiceRecord = ref<PracticeRecord | null>(null)

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value] || null
})

const correctCount = computed(() => {
  return questions.value.filter(q => q.isCorrect === true).length
})

const incorrectCount = computed(() => {
  return questions.value.filter(q => q.isCorrect === false).length
})

const skipCount = computed(() => {
  return questions.value.filter(q => q.isCorrect === undefined).length
})

const accuracyRate = computed(() => {
  const answeredCount = correctCount.value + incorrectCount.value
  return answeredCount > 0 ? Math.round((correctCount.value / answeredCount) * 100) : 0
})

const incorrectQuestions = computed(() => {
  return questions.value
    .filter(q => q.isCorrect === false)
    .map(q => ({ ...q, index: questions.value.indexOf(q) + 1 }))
})

const categoryMastery = computed(() => {
  const mastery: Record<string, { correctCount: number; totalCount: number; correctRate: number }> = {}
  
  questions.value.forEach(question => {
    if (!mastery[question.categoryId]) {
      mastery[question.categoryId] = { correctCount: 0, totalCount: 0, correctRate: 0 }
    }
    mastery[question.categoryId].totalCount++
    if (question.isCorrect) {
      mastery[question.categoryId].correctCount++
    }
  })
  
  // 计算正确率
  Object.keys(mastery).forEach(categoryId => {
    const m = mastery[categoryId]
    m.correctRate = m.totalCount > 0 ? Math.round((m.correctCount / m.totalCount) * 100) : 0
  })
  
  return mastery
})

// 方法
const getCategoryName = (categoryId: string) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未知分类'
}

const getProgressColor = (rate: number) => {
  if (rate >= 80) return '#67c23a'
  if (rate >= 60) return '#e6a23c'
  if (rate >= 40) return '#f56c6c'
  return '#ff4949'
}

const getQuestionTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    blank: '填空题',
    essay: '简答题'
  }
  return typeMap[type] || type
}

const getDifficultyText = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return difficultyMap[difficulty] || difficulty
}

const getOptionLabel = (index: number) => {
  return String.fromCharCode(65 + index)
}

const getCorrectAnswerDisplay = () => {
  if (!currentQuestion.value) return ''
  
  if (currentQuestion.value.type === 'blank' || currentQuestion.value.type === 'essay') {
    return currentQuestion.value.correctAnswers.join('、')
  } else if (currentQuestion.value.options) {
    return currentQuestion.value.correctAnswers
      .map(answer => {
        if (typeof answer === 'number') {
          return getOptionLabel(answer) + '.' + currentQuestion.value.options![answer]
        }
        return answer
      })
      .join('，')
  }
  return ''
}

const getAccuracyColor = (rate: number) => {
  if (rate >= 90) return '#67c23a'
  if (rate >= 70) return '#e6a23c'
  if (rate >= 60) return '#f56c6c'
  return '#ff4949'
}

const getMasteryColor = (rate: number) => {
  return getAccuracyColor(rate)
}

const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

const formatProgress = (percentage: number) => {
  return `${percentage}%`
}

const selectCategory = (categoryId: string) => {
  currentCategory.value = categoryId
}

const onCategoryChange = () => {
  // 分类切换时的逻辑
}

const selectPracticeMode = (modeId: string) => {
  currentMode.value = modeId
}

const startPractice = () => {
  isLoading.value = true
  
  // 模拟加载题目
  setTimeout(() => {
    // 生成练习题目
    generatePracticeQuestions()
    
    // 初始化练习状态
    isPracticing.value = true
    showResult.value = false
    currentQuestionIndex.value = 0
    selectedOptions.value = []
    textAnswer.value = ''
    isAnswered.value = false
    isMarked.value = false
    showExplanation.value = false
    practiceTimer.value = 0
    totalPracticeTime.value = 0
    
    // 开始计时
    startTimer()
    
    isLoading.value = false
  }, 1000)
}

const generatePracticeQuestions = () => {
  // 这里简化处理，实际应该根据分类、难度等条件从题库中筛选题目
  let filteredQuestions = [...mockQuestions]
  
  // 根据分类筛选
  if (currentCategory.value !== 'all') {
    filteredQuestions = filteredQuestions.filter(q => q.categoryId === currentCategory.value)
  }
  
  // 根据难度筛选
  if (difficultyLevel.value === 1) {
    filteredQuestions = filteredQuestions.filter(q => q.difficulty === 'easy')
  } else if (difficultyLevel.value === 2) {
    filteredQuestions = filteredQuestions.filter(q => q.difficulty === 'easy' || q.difficulty === 'medium')
  } else if (difficultyLevel.value === 3) {
    filteredQuestions = filteredQuestions.filter(q => q.difficulty === 'medium' || q.difficulty === 'hard')
  }
  
  // 随机排序
  filteredQuestions.sort(() => Math.random() - 0.5)
  
  // 截取指定数量的题目
  questions.value = filteredQuestions.slice(0, questionCount.value)
}

const startTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
  }
  
  timerInterval.value = window.setInterval(() => {
    practiceTimer.value++
  }, 1000)
}

const stopTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
    timerInterval.value = null
  }
}

const selectOption = (index: number) => {
  if (isAnswered.value) return
  
  const question = currentQuestion.value
  if (!question) return
  
  if (question.type === 'single') {
    // 单选题只能选择一个选项
    selectedOptions.value = [index]
  } else if (question.type === 'multiple') {
    // 多选题可以选择多个选项
    const optionIndex = selectedOptions.value.indexOf(index)
    if (optionIndex > -1) {
      selectedOptions.value.splice(optionIndex, 1)
    } else {
      selectedOptions.value.push(index)
    }
  }
}

const submitAnswer = () => {
  const question = currentQuestion.value
  if (!question || isAnswered.value) return
  
  isSubmitting.value = true
  
  // 模拟提交答案的延迟
  setTimeout(() => {
    let isCorrect = false
    
    if (question.type === 'single' || question.type === 'multiple') {
      // 比较选项答案
      isCorrect = selectedOptions.value.length === question.correctAnswers.length &&
        selectedOptions.value.every(option => 
          Array.isArray(question.correctAnswers) && 
          question.correctAnswers.some(correct => 
            typeof correct === 'number' && typeof option === 'number' && correct === option
          )
        )
      
      // 保存用户答案
      question.userAnswers = [...selectedOptions.value]
    } else if (question.type === 'blank' || question.type === 'essay') {
      // 简单的文本答案比较
      isCorrect = question.correctAnswers.some(answer => {
        if (typeof answer === 'string') {
          return textAnswer.value.toLowerCase().includes(answer.toLowerCase())
        }
        return false
      })
      
      // 保存用户答案
      question.userAnswers = [textAnswer.value]
    }
    
    // 更新题目状态
    question.isCorrect = isCorrect
    isAnswered.value = true
    
    // 显示解析
    showExplanation.value = true
    
    isSubmitting.value = false
  }, 500)
}

const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    saveCurrentQuestionState()
    currentQuestionIndex.value--
    loadCurrentQuestionState()
  }
}

const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    saveCurrentQuestionState()
    currentQuestionIndex.value++
    loadCurrentQuestionState()
  } else {
    // 最后一题，结束练习
    endPractice()
  }
}

const saveCurrentQuestionState = () => {
  const question = currentQuestion.value
  if (!question) return
  
  // 这里可以保存当前题目的状态
}

const loadCurrentQuestionState = () => {
  const question = currentQuestion.value
  if (!question) return
  
  // 加载题目状态
  selectedOptions.value = question.userAnswers as number[] || []
  textAnswer.value = question.userAnswers?.[0] as string || ''
  isAnswered.value = question.isCorrect !== undefined
  showExplanation.value = isAnswered.value
}

const skipQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    nextQuestion()
  }
}

const toggleMark = () => {
  isMarked.value = !isMarked.value
}

const toggleExplanation = () => {
  showExplanation.value = !showExplanation.value
}

const endPracticeEarly = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要提前结束练习吗？',
      '确认结束',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续练习',
        type: 'warning'
      }
    )
    
    endPractice()
  } catch (error) {
    // 用户取消操作
  }
}

const endPractice = () => {
  // 停止计时
  stopTimer()
  totalPracticeTime.value = practiceTimer.value
  
  // 保存练习记录
  savePracticeRecord()
  
  // 显示练习结果
  isPracticing.value = false
  showResult.value = true
}

const savePracticeRecord = () => {
  practiceRecord.value = {
    id: `practice-${Date.now()}`,
    categoryId: currentCategory.value,
    mode: currentMode.value,
    questionCount: questions.value.length,
    correctCount: correctCount.value,
    incorrectCount: incorrectCount.value,
    skipCount: skipCount.value,
    accuracyRate: accuracyRate.value,
    totalTime: totalPracticeTime.value,
    startTime: new Date(Date.now() - totalPracticeTime.value * 1000),
    endTime: new Date(),
    questions: [...questions.value]
  }
}

const reviewIncorrectQuestion = (_question: any) => {
  // 在实际应用中，这里应该跳转到错题详情页面
  ElMessage.info('查看错题详情功能待实现')
}

const reviewAllQuestions = () => {
  // 在实际应用中，这里应该跳转到所有题目回顾页面
  ElMessage.info('查看全部题目功能待实现')
}

const saveToErrorBook = () => {
  if (incorrectQuestions.value.length === 0) {
    ElMessage.warning('没有错题需要保存')
    return
  }
  
  // 模拟保存到错题本
  ElMessage.success(`已保存 ${incorrectQuestions.value.length} 道错题到错题本`)
}

const practiceAgain = () => {
  // 重新开始练习
  startPractice()
}

const finishPractice = () => {
  // 完成练习，返回练习首页
  showResult.value = false
  isPracticing.value = false
  
  // 在实际应用中，这里可以跳转到练习历史页面或其他相关页面
}

const refreshPractice = () => {
  // 刷新练习页面
  ElMessage.success('练习页面已刷新')
}

const viewPracticeHistory = () => {
  // 在实际应用中，这里应该跳转到练习历史页面
  ElMessage.info('查看练习历史功能待实现')
}

// 组件挂载时初始化
onMounted(() => {
  // 可以在这里加载用户的练习数据、知识点掌握情况等
})

// 组件卸载时清理
onUnmounted(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
  }
})
</script>

<style lang="scss" scoped>
.knowledge-practice-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.category-navigation {
  margin-bottom: 30px;
}

.category-card {
  border-radius: 12px;
  overflow: hidden;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  flex-wrap: wrap;
  gap: 15px;
}

.category-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.category-progress-list {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.category-progress-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 20px;
  flex-wrap: wrap;
  &:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
  &.active {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
}

.category-info {
  flex: 1;
  min-width: 200px;
}

.category-name {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10px;
}

.category-stats {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #6b7280;
}

.category-progress {
  width: 200px;
  flex-shrink: 0;
}

.practice-mode-section {
  margin-bottom: 30px;
}

.practice-mode-card {
  border-radius: 12px;
  overflow: hidden;
  padding: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 20px 0;
}

.practice-mode-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.practice-mode-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: center;
  &:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
    transform: translateY(-2px);
  }
  &.active {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
}

.mode-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.mode-name {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10px;
}

.mode-description {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.6;
}

.practice-settings-section {
  margin-bottom: 30px;
}

.settings-card {
  border-radius: 12px;
  overflow: hidden;
  padding: 20px;
}

.settings-content {
  display: flex;
  gap: 40px;
  align-items: center;
  flex-wrap: wrap;
}

.setting-group {
  display: flex;
  align-items: center;
  gap: 15px;
}

.setting-label {
  font-size: 16px;
  color: #1f2937;
  min-width: 80px;
}

.start-practice-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  padding: 40px;
}

.start-practice-btn {
  font-size: 18px;
  padding: 15px 40px;
}

.practicing-section {
  margin-bottom: 30px;
}

.practicing-card {
  border-radius: 12px;
  overflow: hidden;
}

.practice-progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e5e7eb;
  flex-wrap: wrap;
  gap: 15px;
}

.progress-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.progress-text {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.timer-text {
  font-size: 16px;
  color: #6b7280;
}

.progress-buttons {
  display: flex;
  gap: 10px;
}

.question-content {
  padding: 30px;
}

.question-header {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.question-type {
  font-size: 14px;
  color: #6b7280;
  background-color: #f5f7fa;
  padding: 5px 12px;
  border-radius: 16px;
}

.question-difficulty {
  font-size: 14px;
  padding: 5px 12px;
  border-radius: 16px;
}

.difficulty-easy {
  color: #67c23a;
  background-color: #f0f9eb;
}

.difficulty-medium {
  color: #e6a23c;
  background-color: #fdf6ec;
}

.difficulty-hard {
  color: #f56c6c;
  background-color: #fef0f0;
}

.question-stem {
  margin-bottom: 30px;
}

.question-stem h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.6;
  margin: 0 0 15px 0;
}

.question-image {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.question-image img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 30px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 15px 20px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  &:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
  &.selected {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
  &.disabled {
    cursor: not-allowed;
    opacity: 0.8;
  }
}

.option-label {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  min-width: 24px;
  text-align: center;
}

.option-content {
  font-size: 16px;
  color: #4b5563;
  line-height: 1.6;
}

.question-answer-input {
  margin-bottom: 30px;
}

.question-explanation {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 30px;
}

.question-explanation h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 10px 0;
}

.question-explanation p {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.6;
  margin: 0 0 15px 0;
}

.correct-answer {
  font-size: 14px;
  font-weight: 600;
  color: #67c23a;
}

.question-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-top: 1px solid #e5e7eb;
  flex-wrap: wrap;
  gap: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.navigation-buttons {
  display: flex;
  gap: 15px;
}

.practice-result-section {
  margin-bottom: 30px;
}

.result-card {
  border-radius: 12px;
  overflow: hidden;
}

.result-header {
  padding: 30px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e5e7eb;
}

.result-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  text-align: center;
  margin: 0 0 30px 0;
}

.result-stats {
  display: flex;
  justify-content: center;
  gap: 40px;
  flex-wrap: wrap;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.result-content {
  padding: 30px;
}

.chart-container {
  text-align: center;
  margin-bottom: 40px;
}

.chart-container h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 30px 0;
}

.chart-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.incorrect-questions {
  margin-bottom: 40px;
}

.incorrect-questions h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 20px 0;
}

.incorrect-questions-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.incorrect-question-item {
  padding: 20px;
  border: 1px solid #f56c6c;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  &:hover {
    background-color: #fef0f0;
  }
}

.incorrect-question-header {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
}

.question-number {
  font-size: 14px;
  font-weight: 600;
  color: #f56c6c;
}

.incorrect-question-stem {
  font-size: 16px;
  color: #4b5563;
  line-height: 1.6;
}

.knowledge-mastery h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 20px 0;
}

.mastery-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.mastery-item {
  padding: 15px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.mastery-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.mastery-category {
  font-size: 16px;
  color: #1f2937;
}

.mastery-rate {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 30px;
  border-top: 1px solid #e5e7eb;
  flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .practice-mode-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
  
  .settings-content {
    flex-direction: column;
    align-items: stretch;
    gap: 20px;
  }
  
  .result-stats {
    gap: 20px;
  }
  
  .question-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .navigation-buttons {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .category-progress-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .category-progress {
    width: 100%;
  }
  
  .practice-mode-grid {
    grid-template-columns: 1fr;
  }
  
  .result-stats {
    flex-direction: column;
    align-items: center;
  }
  
  .result-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .question-content {
    padding: 20px;
  }
  
  .question-header {
    flex-direction: column;
    gap: 10px;
  }
}
</style>